package com.my.java8;

import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.LongStream;

public class ParallelTest {

	public static long measureSumPerf(Function<Long, Long> adder, long n) {
		long fastest = Long.MAX_VALUE;
		for (int i = 0; i < 10; i++) {
			long start = System.nanoTime();
			long sum = adder.apply(n);
			long duration = (System.nanoTime() - start) / 1_000_000;
			//System.out.println("Result: " + sum);
			if (duration < fastest)
				fastest = duration;
		}
		return fastest;
	}
	
	public static long rangedSum(long n) {return LongStream.rangeClosed(1, n)
			.reduce(0L, Long::sum);
	}
	
	public static long parallelRangedSum(long n) {
		return LongStream.rangeClosed(1, n)
		.parallel()
		.reduce(0L, Long::sum);
		}

	public static void main(String[] args) {
		System.out.println(Runtime.getRuntime().availableProcessors());
		//StreamSupport.stream(spliterator, parallel)
		
		System.out.println("Parallel range sum done in: " +
				measureSumPerf(ParallelTest::parallelRangedSum, 10_000_000) +
				" msecs");
		
		System.out.println(" range sum done in: " +
				measureSumPerf(ParallelTest::rangedSum, 10_000_000) +
				" msecs");
		
		
		int a=2;
		Runnable r = ()->{
			//int a=3;
		};
		
		Supplier<String> sp = ()->"";
	}

}
